#ifndef DUMP_H
#define DUMP_H

#include <memory>
#include <string>

#include "SCGI.h"
#include "Util.h"

class ADump
	: public scgi::Application
	, public std::enable_shared_from_this<ADump>
{
public:
	typedef std::shared_ptr<ADump> pointer;

private:
	std::string buffer;

public:
	virtual void start()
	{
	}

	virtual void push(char * first_, char * last_)
	{
		scgi::URLDecoder decode;
		buffer.append(decode(first_, last_));
	}

	virtual void eos()
	{
		scgi::Session::pointer session = get_session();

		if(!session)
			session = create_session(now() + scgi::Time::seconds(60));

		request->cookie.set("sid", session->get_sid_string());
		request->cookie.path = "/";
		request->cookie.expires = session->expires;
		request->cookie.secure = false;

		buffer =
			"Status: 200 OK\r\n";
		buffer += request->cookie.to_string();
		buffer +=
			"Content-type: text/plain\r\n"
			"\r\n";

		buffer +=
			  "\r\n[request-path]\r\n"
			+ std::string("path: ") + request->path.path + "\r\n"
			+ "file: " + request->path.file + "\r\n"
			+ "query: " + request->path.query + "\r\n";

		buffer += "\r\n[request]\r\n";
		std::map<std::string, std::string>::const_iterator
			it1 = request->env.begin();
		while(it1 != request->env.end())
		{
			buffer += it1->first + ": " + it1->second + "\r\n";
			++it1;
		}

		buffer += "\r\n[cookie]\r\n";
		buffer += request->cookie.to_string() + "\r\n";
		
		buffer += "\r\n[session_table]\r\n";
		buffer += std::string("cache_size: ")
			+ scgi::to_string(get_cached_session_size()) + "\r\n";

		buffer += "\r\n[session]\r\n";
		buffer += std::string("sid: ") + session->get_sid_string() + "\r\n";
		buffer +=
			  std::string("expires: ")
			+ session->expires.to_cookie_string() + "\r\n";

		std::map<std::string, std::string>::const_iterator
			it2 = session->table.begin();
		while(it2 != session->table.end())
		{
			buffer += it2->first + ": " + it2->second + "\r\n";
			++it2;
		}

		write(buffer, this, &ADump::finish);

		set_session(session);
	}

	void finish() { close_socket(); }
};

class FDump : public scgi::Factory
{
public:
	typedef std::shared_ptr<FDump> pointer;

public:
	virtual std::string name() const { return "dump"; }
	virtual scgi::Application::pointer create_application()
	{
		return scgi::Application::pointer(new ADump);
	}

	static Factory::pointer create() { return Factory::pointer(new FDump); }
};

#endif // DUMP_H
